package com.ytkj.digitalConstruction.util;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 拼音工具类
 * 
 * @author Pete
 * @Date 2018年1月9日
 */
public class PinYinUtil {

	private final static Logger log = LoggerFactory.getLogger(PinYinUtil.class);

	private final static HanyuPinyinOutputFormat hypyopf = new HanyuPinyinOutputFormat();

	static {
		hypyopf.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
	}

	/**
	 * 将用户姓名转换成用户名
	 * 
	 * @param name
	 * @return
	 * @throws BadHanyuPinyinOutputFormatCombination
	 */
	public static String toUserName(String name) {
		int num = name.indexOf("(")  +  name.indexOf("（") + 1;
		if (num != -1) {
			name = name.substring(0, num);
		}
		char[] chs = name.toCharArray();
		int len = chs.length;
		StringBuilder sb = new StringBuilder();
		if (len == 0) {
			return sb.toString();
		}
		String[] strs = new String[len];
		for (int i = 0; i < len; i++) {
			String[] ss = null;
			try {
				ss = PinyinHelper.toHanyuPinyinStringArray(name.charAt(i), hypyopf);
			} catch (BadHanyuPinyinOutputFormatCombination e) {
				e.printStackTrace();
				// TODO 添加log打印错误日志
				log.error("PinyinUtil Exception: PinyinUtil.toUserName faild!");
			}
			if (ss.length == 0) {
				continue;
			}
			if (i != 0 && len > 2) {
				strs[i] = String.valueOf(ss[0].charAt(0));
			} else {
				strs[i] = ss[0];
			}
		}
		for (String str : strs) {
			sb.append(str);
		}
		return sb.toString();
	}

	public static void main(String[] args) throws Exception {
		System.out.println(toUserName("包阿儒汉(哈哈哈哈)"));
		System.out.println(toUserName("刘海涛（哈哈哈哈）"));
		System.out.println(toUserName("王浩（"));
	}

}
